package com.zb.zeus.auth.controller;

import com.zb.zeus.auth.form.LoginBody;
import com.zb.zeus.auth.remote.RemoteZbPempService;
import com.zb.zeus.auth.service.SysLoginService;
import com.zb.zeus.common.core.domain.R;
import com.zb.zeus.common.core.utils.StringUtils;
import com.zb.zeus.common.security.annotation.PreAuthorize;
import com.zb.zeus.common.security.context.UserContextHolder;
import com.zb.zeus.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * token 控制
 *
 * @author zb.zeus
 */
@Slf4j
@RestController
@Api(value = "token控制器", tags = "token控制器")
public class TokenController {

    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private RemoteZbPempService remoteZbPempService;

    @ResponseBody
    @GetMapping(value = "feishu/login")
    public void login(String code, String state, HttpServletResponse response) throws IOException {
        // 用户登录
        String[] states = state.split(",");
        R r = remoteZbPempService.getUserIdByAccessToken(code);
        LoginUser userInfo = sysLoginService.login(r.getData().toString());
        Map<String, Object> token = sysLoginService.createToken(userInfo);
        String redirectUrl = "";
        for (int i = 0; i < states.length; i++) {
            if (i == 0) {
                //固定参数
                redirectUrl += (states[i] + "?t=" + token.get("access_token").toString() + "&userName=" + r.getData().toString());
            } else {
                //自定义参数
                String[] split = states[i].split("=");
                redirectUrl += ("&" + split[0] + "=" + split[1]);
            }
        }
        response.sendRedirect(redirectUrl);
    }

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(sysLoginService.createToken(userInfo));
    }

    @PreAuthorize
    @DeleteMapping("logout")
    public R<?> logout() {
        LoginUser loginUser = UserContextHolder.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            sysLoginService.delToken(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PreAuthorize(hasPermi = "*:*:*")
    @PostMapping("refresh")
    public R<?> refresh() {
        LoginUser loginUser = UserContextHolder.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            sysLoginService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }
}
